package com.msdp.controller;


import com.msdp.dto.LoginFormDTO;
import com.msdp.dto.Result;
import com.msdp.dto.UserDTO;
import com.msdp.entity.User;
import com.msdp.entity.UserInfo;
import com.msdp.service.IUserInfoService;
import com.msdp.service.IUserService;
import com.msdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    /**
     * 发送手机验证码
     */
//    @PostMapping("code")
//    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
//        return userService.sendCode(phone, session);
//    }

    /**
     * 发送邮箱验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        return userService.sendEmailCode(phone, session);
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        return userService.login(loginForm, session);
    }

    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(){
        UserHolder.removeUser();
        return Result.ok();
    }

    @GetMapping("/me")
    public Result me(){
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable("id") Long userId){
        return userService.getUserById(userId);
    }

    /**
     * 用户签到
     * @return
     */
    @PostMapping("/sign")
    public Result sign(){
        return userService.sign();
    }

    /**
     * 判断用户是否签到
     * @return
     */
    @GetMapping("/isSign")
    public Result isSign(){
        return userService.isSign();
    }

    /**
     * 统计用户连续签到天数
     * @return
     */
    @GetMapping("/sign/count")
    public Result signCount(){
        return userService.signCount();
    }

    /**
     * 根据id批量查询用户
     * @return
     */
    @GetMapping("/users")
    public Result getBatchUser(){
        // 查询详情
        List<User> users = userService.getUsersById();
        // 返回
        return Result.ok(users);
    }
}
